use anyhow::Result;
use log::info;
use rocksdb::{DB, Options};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};

pub type Db = Arc<DB>;

// 数据库管理器
pub struct DatabaseManager {
    databases: Mutex<HashMap<String, Db>>,
    base_path: String,
}

impl DatabaseManager {
    pub fn new(base_path: String) -> Self {
        Self {
            databases: Mutex::new(HashMap::new()),
            base_path,
        }
    }

    pub fn get_db(&self, name: &str) -> Result<Db> {
        let mut databases = self.databases.lock().expect("数据库映射互斥锁被毒化");

        if let Some(db) = databases.get(name) {
            return Ok(db.clone());
        }

        // 创建新的数据库
        info!("加载数据库: {}", name);
        let mut opts = Options::default();
        opts.create_if_missing(true);
        let db_path = format!("{}/{}", self.base_path, name);
        let db = DB::open(&opts, &db_path)?;
        let db = Arc::new(db);

        databases.insert(name.to_string(), db.clone());
        info!("数据库 '{}' 已创建并打开", name);
        Ok(db)
    }
}